﻿using System.Net;
using Common.Authentication;
using Common.Dto;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Common.Middleware;

public class UnAuthorizeExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<UnAuthorizeExceptionMiddleware> _logger;

    public UnAuthorizeExceptionMiddleware(RequestDelegate next, ILogger<UnAuthorizeExceptionMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);

            var statusCode = context.Response.StatusCode;

            if (statusCode == (int)HttpStatusCode.Unauthorized)
            {
                var appAuthFeature = context.Features.Get<AppAuthFeature>();
                var user = context.Request.HttpContext.User;
                var authenticated = user.Identity?.IsAuthenticated ?? false;
                // var appAuthFeature = context.Features.Get<AppAuthFeature>();
                var error = "没有操作权限: " + appAuthFeature?.AuthenticateResult?.Failure?.Message;
                var failure = Result.Failure(error, 200);
                // var errorJson = JsonConvert.SerializeObject(failure);
                context.Response.StatusCode = 200;
                await context.Response.WriteAsJsonAsync(failure);
            }
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message, "AppExceptionMiddleware捕获异常");
            // throw e;
        }
    }
}